package com.kinsin.kinsinutils

import android.Manifest
import android.graphics.Color
import android.os.Bundle
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import com.kinsin.kinsinutil.AppUtils
import com.kinsin.kinsinutil.logD
import com.kinsin.kinsinutil.showToastSafe
import com.kinsin.kinsinutils.databinding.ActivityTestAppUtilsBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class TestAppUtilsActivity : BaseActivity<ActivityTestAppUtilsBinding>(ActivityTestAppUtilsBinding::inflate) {

    // 测试用包名（根据实际情况修改）
    private val launcherPackageName = "com.kinsin.pcdiytool"
    private val testPackageName = "com.android.chrome" // Chrome浏览器包名
    private val systemPackageName = "com.android.settings" // 系统设置包名
    private val testUrl = "https://www.baidu.com"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        runAllTests()
    }

    override fun initFirst() {
    }

    override fun initData() {
    }

    override fun initAction() {
    }

    private fun runAllTests() {
        CoroutineScope(Dispatchers.Main).launch {
            runInstalledAppsTest()
            runAppStateTests()
            runAppOperationsTest()
            runPermissionTest()
            showTestCompletion()
        }
    }

    // region 测试用例
    //================================================================================

    /**
     * 测试应用列表获取功能
     */
    private suspend fun runInstalledAppsTest() {
        // 测试1：获取非系统应用
        val userApps = AppUtils.getInstalledApps(this@TestAppUtilsActivity, includeSystemApp = false)
        logD("AppUtilsTest", "获取用户应用：${userApps.size}个")
        logTestResult("获取用户应用", userApps.isNotEmpty())

        // 测试2：获取全部应用
        val allApps = AppUtils.getInstalledApps(this@TestAppUtilsActivity, includeSystemApp = true)
        logD("AppUtilsTest", "获取全部应用：${allApps.size}个")
        logTestResult("获取全部应用", allApps.size > userApps.size)

        // 测试3：异步获取
        val asyncResult = AppUtils.getInstalledAppsAsync(this@TestAppUtilsActivity).getOrNull()
        logD("AppUtilsTest", "异步获取：${asyncResult?.size}个")
        logTestResult("异步获取应用列表", asyncResult?.isNotEmpty() == true)
    }

    /**
     * 测试应用状态检测
     */
    private fun runAppStateTests() {
        // 测试1：检查应用安装状态
        val isInstalled = AppUtils.isAppInstalled(this, testPackageName)
        logD("AppUtilsTest", "$testPackageName 是否已经安装：$isInstalled")
        logTestResult("应用安装检测", isInstalled)

        // 测试2：检查系统应用状态
        val isSystemDisabled = AppUtils.isAppDisabled(this, systemPackageName)
        logD("AppUtilsTest", "$systemPackageName 是否被禁用：$isSystemDisabled")
        logTestResult("系统应用禁用状态", !isSystemDisabled)
    }

    /**
     * 测试应用操作功能
     */
    private fun runAppOperationsTest() {
        // 测试1：启动应用
        val (launchSuccess, _) = AppUtils.launchApp(this, launcherPackageName)
        logTestResult("启动应用", launchSuccess)

        // 测试2：打开浏览器
        val browserSuccess = AppUtils.openBrowser(this, testUrl)
        logTestResult("打开浏览器", browserSuccess)

        // 测试3：获取版本信息
        val versionInfo = AppUtils.getVersionInfo(this, testPackageName)
        logD("AppUtilsTest", "获取版本信息：$versionInfo")
        logTestResult("获取版本信息", versionInfo?.second ?: 0 > 0)
    }

    /**
     * 测试权限检查功能
     */
    private fun runPermissionTest() {
        // 测试相机权限（需要先在manifest声明）
        val status = AppUtils.checkPermission(
            this,
            Manifest.permission.CAMERA
        )
        val result = when (status) {
            AppUtils.PermissionStatus.GRANTED -> "已授权"
            AppUtils.PermissionStatus.DENIED -> "未授权"
            AppUtils.PermissionStatus.REVOKED_BY_POLICY -> "被策略限制"
        }
        logD("AppUtilsTest", "相机权限状态：$result")
    }
    // endregion

    // region 测试工具方法
    //================================================================================

    private fun logTestResult(testName: String, success: Boolean) {
        val color = if (success) Color.GREEN else Color.RED
        val message = "$testName: ${if (success) "✓" else "✗"}"

        logD("AppUtilsTest", message)
        appendToLogView(message, color)
    }

    private fun appendToLogView(text: String, color: Int) {
        // 如果有显示日志的TextView
        binding.showLog.apply {
            append("\n${SpannableString(text).apply {
                setSpan(ForegroundColorSpan(color), 0, length, 0)
            }}")
        }
    }

    private fun showTestCompletion() {
        showToastSafe("所有测试执行完成")
    }
    // endregion
}